package com.lanchetech.service.impl;


import com.lanchetech.common.enums.ExpTypeEnum;
import com.lanchetech.dao.ExpFlowMapper;
import com.lanchetech.dao.UserMapper;
import com.lanchetech.entity.ExpFlow;
import com.lanchetech.entity.User;
import com.lanchetech.service.ExpService;
import com.lanchetech.service.HonorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;


@Service
public class ExpServiceImpl implements ExpService {

    @Autowired
    ExpFlowMapper expFlowMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    HonorService honorService;

    @Override
    public void createExpFlow(User user, Long relateId, ExpTypeEnum expTypeEnum) {
        // 先查重
        ExpFlow result = expFlowMapper.findOneByUserIdAndRelateIdAndType(user.getId(), relateId, expTypeEnum.getType());
        if(result == null){
            expFlowMapper.insert(ExpFlow.builder()
                    .userId(user.getId())
                    .relateId(relateId)
                    .exp(expTypeEnum.getExp())
                    .type(expTypeEnum.getType())
                    .createdAt(new Date())
                    .build());
            // 增加经验值
            Integer exp  = user.getExp() + expTypeEnum.getExp();
            userMapper.updateExpById(exp, user.getId());

            // 发放勋章
            honorService.createMedalHonor(user, exp);
        }
    }
}